from player import *

class ExamplePlayer(Player):
  def __init__(self):
    Player.__init__(self, "Gabe", "Gabriel Taubman")

  def GetMove(self, board, letters):
    """A simple implementation of GetMove().  Override this in a subclass.
    
    Args:
      board: A Board instance.
      letters: A list of letters that we have to play with.

    Returns:
      A Move containing our desired move.
    """
    # Prepare our move.
    m = Move()

    if len(letters) == 0:
      # If we get no letters, it's the end of the game so signal that we're
      # done.
      m.DoneWithGame()
      return m

    # Get all the valid playing positions on the board.
    valid_positions = board.ValidPositions()

    # If there are no valid positions, it just means it's the beginning of the
    # game.  Our move must contain (0,0) and be greater than 1 letter long.
    if len(valid_positions) == 0:
      for first_letter in letters:
        for second_letter in letters:
          if first_letter == second_letter:
            # This is incorrect if we actually have two of the same letter in
            # our hand, but that's fine.
            continue
          try:
            m.AddLetterAtPosition(first_letter, (0,0))
            m.AddLetterAtPosition(second_letter, (1,0))
            board.ScoreForMove(m)
          except InvalidMoveError:
            m.Clear()
          else:
            return m
      # If we make it to here, we've tried every combination of opening moves
      # that our hand permits, and none were valid.  We must pass or exchange
      # our tiles.
      if random.random() > 0.5:
        m.Pass()
      else:
        m.AddLettersToExchange(letters)
      return m

    for pos in valid_positions:
      for letter in letters:
        m.AddLetterAtPosition(letter, pos)
        try:
          board.ScoreForMove(m)
        except InvalidMoveError:
          m.Clear()
          pass
        else:
          return m

    # If we get here there's no acceptable move.  We could either pass for this
    # turn, or try getting rid of our tiles.
    if random.random() > 0.5:
      m.Pass()
    else:
      m.AddLettersToExchange(letters)
    return m
